package org.study.swing.study01.menu;

import lombok.extern.slf4j.Slf4j;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 弹出式菜单。参考 https://blog.csdn.net/hitmengfanchao/article/details/137032259
 *
 * @author doveylovey
 * @version v1.0.0
 * @email 1135782208@qq.com
 * @date 2024年11月11日
 */
@Slf4j
public class MenuFrame02 extends JFrame implements ActionListener {
    public static void main(String[] args) {
        new MenuFrame02();
    }

    // 创建弹出式菜单
    private JPopupMenu popupMenu = new JPopupMenu("PopupMenu");
    private JTextField textField = new JTextField();
    private JPanel panel = new JPanel();
    private JMenuItem menuItem;

    public MenuFrame02() {
        super.setTitle("弹出式菜单示例");
        super.setSize(600, 400);
        super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // 将窗口居中显示在屏幕上
        super.setLocationRelativeTo(null);
        // 菜单项：Copy
        menuItem = new JMenuItem("Copy");
        menuItem.addActionListener(this);
        popupMenu.add(menuItem);

        // 菜单项：Cut
        menuItem = new JMenuItem("Cut");
        menuItem.addActionListener(this);
        popupMenu.add(menuItem);

        // 菜单项：Paste
        menuItem = new JMenuItem("Paste");
        menuItem.addActionListener(this);
        popupMenu.add(menuItem);

        // 点击面板右键触发弹出式菜单
        panel.setComponentPopupMenu(popupMenu);
        super.add(panel, BorderLayout.CENTER);
        super.add(textField, BorderLayout.SOUTH);
        super.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String command = e.getActionCommand();
        textField.setText(command);
    }
}
